import products from '../mock/products.js';
import user from '../mock/user.js';
import orders from '../mock/orders.js';
import cart from '../mock/cart.js';

// 模拟延迟
const delay = (ms = 500) => {
  return new Promise(resolve => {
    setTimeout(resolve, ms);
  });
};

// 模拟接口响应格式
const success = (data) => {
  return {
    code: 0,
    message: 'success',
    data
  };
};

// 模拟错误响应
const error = (message = '请求失败', code = -1) => {
  return {
    code,
    message,
    data: null
  };
};

// 当前登录状态
let isLoggedIn = false;
let currentUser = null;
let currentCart = [...cart];

// 模拟接口
export default {
  // 商品相关接口
  product: {
    // 获取商品列表
    async getList(params = {}) {
      await delay();
      const { keyword = '', category = '' } = params;
      let result = [...products];
      
      if (keyword) {
        result = result.filter(item => 
          item.name.includes(keyword) || 
          item.description.includes(keyword) ||
          item.category.includes(keyword)
        );
      }
      
      if (category) {
        result = result.filter(item => item.category === category);
      }
      
      return success(result);
    },
    
    // 获取商品详情
    async getDetail(id) {
      await delay();
      const product = products.find(item => item.id === id);
      if (product) {
        return success(product);
      }
      return error('商品不存在');
    },
    
    // 获取商品分类
    async getCategories() {
      await delay();
      const categories = [...new Set(products.map(item => item.category))];
      return success(categories);
    }
  },
  
  // 用户相关接口
  user: {
    // 登录
    async login(params = {}) {
      await delay(800);
      const { type, phone, code, wxCode } = params;
      
      // 模拟登录成功
      isLoggedIn = true;
      currentUser = { ...user };
      
      return success({
        token: currentUser.token,
        userInfo: {
          id: currentUser.id,
          nickname: currentUser.nickname,
          avatar: currentUser.avatar,
          phone: currentUser.phone
        }
      });
    },
    
    // 退出登录
    async logout() {
      await delay();
      isLoggedIn = false;
      currentUser = null;
      return success(null);
    },
    
    // 获取用户信息
    async getUserInfo() {
      await delay();
      if (!isLoggedIn) {
        return error('用户未登录', 401);
      }
      return success({
        id: currentUser.id,
        nickname: currentUser.nickname,
        avatar: currentUser.avatar,
        phone: currentUser.phone
      });
    },
    
    // 获取收货地址列表
    async getAddressList() {
      await delay();
      if (!isLoggedIn) {
        return error('用户未登录', 401);
      }
      return success(currentUser.addresses);
    },
    
    // 添加收货地址
    async addAddress(address) {
      await delay();
      if (!isLoggedIn) {
        return error('用户未登录', 401);
      }
      
      const newAddress = {
        id: String(Date.now()),
        ...address,
        isDefault: address.isDefault || false
      };
      
      // 如果设为默认地址，则将其他地址设为非默认
      if (newAddress.isDefault) {
        currentUser.addresses.forEach(item => {
          item.isDefault = false;
        });
      }
      
      currentUser.addresses.push(newAddress);
      return success(newAddress);
    },
    
    // 编辑收货地址
    async updateAddress(address) {
      await delay();
      if (!isLoggedIn) {
        return error('用户未登录', 401);
      }
      
      const index = currentUser.addresses.findIndex(item => item.id === address.id);
      if (index === -1) {
        return error('地址不存在');
      }
      
      // 如果设为默认地址，则将其他地址设为非默认
      if (address.isDefault) {
        currentUser.addresses.forEach(item => {
          item.isDefault = false;
        });
      }
      
      currentUser.addresses[index] = { ...currentUser.addresses[index], ...address };
      return success(currentUser.addresses[index]);
    },
    
    // 删除收货地址
    async deleteAddress(id) {
      await delay();
      if (!isLoggedIn) {
        return error('用户未登录', 401);
      }
      
      const index = currentUser.addresses.findIndex(item => item.id === id);
      if (index === -1) {
        return error('地址不存在');
      }
      
      currentUser.addresses.splice(index, 1);
      return success(null);
    }
  },
  
  // 购物车相关接口
  cart: {
    // 获取购物车列表
    async getList() {
      await delay();
      if (!isLoggedIn) {
        return error('用户未登录', 401);
      }
      return success(currentCart);
    },
    
    // 添加商品到购物车
    async add(params) {
      await delay();
      if (!isLoggedIn) {
        return error('用户未登录', 401);
      }
      
      const { productId, specificationId, count = 1 } = params;
      const product = products.find(item => item.id === productId);
      
      if (!product) {
        return error('商品不存在');
      }
      
      const specification = product.specifications.find(item => item.id === specificationId);
      
      if (!specification) {
        return error('商品规格不存在');
      }
      
      // 检查购物车中是否已存在该商品
      const existIndex = currentCart.findIndex(item => 
        item.productId === productId && item.specificationId === specificationId
      );
      
      if (existIndex !== -1) {
        // 已存在，增加数量
        currentCart[existIndex].count += count;
        return success(currentCart[existIndex]);
      } else {
        // 不存在，添加新商品
        const newItem = {
          id: 'C' + Date.now(),
          productId,
          name: product.name,
          specificationId,
          specificationName: specification.name,
          price: specification.price,
          count,
          selected: true,
          image: product.images[0]
        };
        
        currentCart.push(newItem);
        return success(newItem);
      }
    },
    
    // 更新购物车商品
    async update(params) {
      await delay();
      if (!isLoggedIn) {
        return error('用户未登录', 401);
      }
      
      const { id, count, selected } = params;
      const index = currentCart.findIndex(item => item.id === id);
      
      if (index === -1) {
        return error('购物车商品不存在');
      }
      
      if (count !== undefined) {
        currentCart[index].count = count;
      }
      
      if (selected !== undefined) {
        currentCart[index].selected = selected;
      }
      
      return success(currentCart[index]);
    },
    
    // 删除购物车商品
    async remove(id) {
      await delay();
      if (!isLoggedIn) {
        return error('用户未登录', 401);
      }
      
      const index = currentCart.findIndex(item => item.id === id);
      
      if (index === -1) {
        return error('购物车商品不存在');
      }
      
      currentCart.splice(index, 1);
      return success(null);
    },
    
    // 全选/取消全选
    async selectAll(selected = true) {
      await delay();
      if (!isLoggedIn) {
        return error('用户未登录', 401);
      }
      
      currentCart.forEach(item => {
        item.selected = selected;
      });
      
      return success(currentCart);
    },
    
    // 清空购物车
    async clear() {
      await delay();
      if (!isLoggedIn) {
        return error('用户未登录', 401);
      }
      
      currentCart = [];
      return success(null);
    }
  },
  
  // 订单相关接口
  order: {
    // 获取订单列表
    async getList(params = {}) {
      await delay();
      if (!isLoggedIn) {
        return error('用户未登录', 401);
      }
      
      const { status } = params;
      let result = [...orders];
      
      if (status !== undefined) {
        result = result.filter(item => item.status === status);
      }
      
      return success(result);
    },
    
    // 获取订单详情
    async getDetail(id) {
      await delay();
      if (!isLoggedIn) {
        return error('用户未登录', 401);
      }
      
      const order = orders.find(item => item.id === id);
      
      if (!order) {
        return error('订单不存在');
      }
      
      return success(order);
    },
    
    // 创建订单
    async create(params) {
      await delay(1000);
      if (!isLoggedIn) {
        return error('用户未登录', 401);
      }
      
      const { addressId, cartIds } = params;
      
      // 验证地址
      const address = currentUser.addresses.find(item => item.id === addressId);
      if (!address) {
        return error('收货地址不存在');
      }
      
      // 获取购物车商品
      let orderProducts = [];
      let totalAmount = 0;
      
      if (cartIds && cartIds.length > 0) {
        // 从购物车创建订单
        const selectedItems = currentCart.filter(item => cartIds.includes(item.id));
        
        if (selectedItems.length === 0) {
          return error('未选择商品');
        }
        
        orderProducts = selectedItems.map(item => {
          totalAmount += item.price * item.count;
          return {
            id: item.productId,
            name: item.name,
            specificationId: item.specificationId,
            specificationName: item.specificationName,
            price: item.price,
            count: item.count,
            image: item.image
          };
        });
        
        // 从购物车中移除已下单商品
        currentCart = currentCart.filter(item => !cartIds.includes(item.id));
      } else {
        return error('参数错误');
      }
      
      // 创建新订单
      const newOrder = {
        id: 'O' + Date.now(),
        userId: currentUser.id,
        products: orderProducts,
        totalAmount,
        status: 1, // 待付款
        address,
        createTime: new Date().toLocaleString(),
        payTime: null,
        deliveryTime: null,
        completeTime: null
      };
      
      // 添加到订单列表
      orders.unshift(newOrder);
      
      return success(newOrder);
    },
    
    // 支付订单
    async pay(id) {
      await delay(1500);
      if (!isLoggedIn) {
        return error('用户未登录', 401);
      }
      
      const orderIndex = orders.findIndex(item => item.id === id);
      
      if (orderIndex === -1) {
        return error('订单不存在');
      }
      
      if (orders[orderIndex].status !== 1) {
        return error('订单状态错误');
      }
      
      // 更新订单状态
      orders[orderIndex].status = 2; // 待发货
      orders[orderIndex].payTime = new Date().toLocaleString();
      
      return success(orders[orderIndex]);
    },
    
    // 确认收货
    async confirm(id) {
      await delay();
      if (!isLoggedIn) {
        return error('用户未登录', 401);
      }
      
      const orderIndex = orders.findIndex(item => item.id === id);
      
      if (orderIndex === -1) {
        return error('订单不存在');
      }
      
      if (orders[orderIndex].status !== 3) {
        return error('订单状态错误');
      }
      
      // 更新订单状态
      orders[orderIndex].status = 4; // 已完成
      orders[orderIndex].completeTime = new Date().toLocaleString();
      
      return success(orders[orderIndex]);
    },
    
    // 取消订单
    async cancel(id) {
      await delay();
      if (!isLoggedIn) {
        return error('用户未登录', 401);
      }
      
      const orderIndex = orders.findIndex(item => item.id === id);
      
      if (orderIndex === -1) {
        return error('订单不存在');
      }
      
      if (orders[orderIndex].status !== 1) {
        return error('只能取消待付款订单');
      }
      
      // 从订单列表中移除
      orders.splice(orderIndex, 1);
      
      return success(null);
    }
  }
}; 